package leetcode.hard;

import leetcode.base.ListNode;


/**
 * ClassName: $25_ReverseKGroup
 * Description:
 * date: 2022-02-14 9:52
 *
 * @author liyifan
 */
public class $25_ReverseKGroup {
    public ListNode reverseKGroup1(ListNode head, int k) {
        ListNode hair = new ListNode(-1);
        hair.next = head;
        ListNode pre = hair;

        while (head != null) {
            ListNode tail = pre;
            for (int i = 0;i < k;i++) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            ListNode nex = tail.next;
            ListNode[] reverse = reverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            pre.next = head;
            tail.next = nex;
            pre = tail;
            head = tail.next;
        }
        return hair.next;
    }

    private ListNode[] reverse(ListNode head, ListNode tail){
        ListNode prev = tail.next;
        ListNode p = head;
        while (prev != tail) {
            ListNode next = prev.next;
            p.next = prev;
            prev = p;
            p = next;
        }
        return new ListNode[]{tail, head};
    }

    private ListNode reverseFromTo(ListNode head, ListNode tail) {
        ListNode prev = null;
        ListNode cur = head;
        ListNode next = head;
        while (cur != tail) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) return null;

        ListNode a , b;
        a = b = head;
        for (int i = 0;i < k;i++) {
            if (b == null) {
                return head;
            }
            b = b.next;
        }
        ListNode newHead = reverseFromTo(a, b);

        a.next = reverseKGroup(b, k);
        return newHead;
    }
}
